<template>
  <a-modal :open="open" width="1200px" ok-text="保存" :ok-button-props="{ disabled: !isCompleted }" centered @ok="onOk" @cancel="onCancel">
    <template #title>
      <div class="flex items-center !-mt-1 w-1/3 justify-between">
        <div>预约安排</div>
        <!-- <a-radio-group v-if="!rowData.brId" v-model:value="sourceType" class="ml-4" button-style="solid" @change="getPatientList">
          <a-radio-button :value="0">门诊</a-radio-button>
          <a-radio-button :value="1">住院</a-radio-button>
        </a-radio-group> -->
      </div>
    </template>
    <div class="flex">
      <div v-if="!rowData.brId" class="w-1/3 pr-3 border-r border-dashed">
        <a-input-search v-model:value="searchKey" placeholder="姓名/助记码/床位号/住院号" @search="getPatientList" />
        <a-spin :spinning="loading" wrapper-class-name="mt-2">
          <div class="card-box -mr-1">
            <div v-if="!dataSource.length" class="w-full h-full flex-center">
              <a-empty />
            </div>
            <template v-for="item in dataSource" :key="item">
              <a-card
                bordered
                :class="{ 'card-item mr-1': true, active: item.brId === formState.brId }"
                :body-style="{ padding: 0 }"
                @click="onSelectPatient(item)"
              >
                <div class="item-header items-center">
                  <a-avatar :src="avatarMan" />
                  <div class="flex-1 ml-2 flex-between">
                    <div class="font-semibold">{{ item.brName || '姓名' }}</div>
                    <div>{{ item.brXb }}</div>
                    <div>{{ item.brAge }}</div>
                    <div class="truncate w-24">{{ item.brMob || '' }}</div>
                    <div>{{ item.admissionCode }}</div>
                  </div>
                </div>
                <div class="p-2">
                  <template v-if="item.inplsh">
                    <LabelValue label-class="text-right w-20" label="科室" :value="item.ksmc" />
                    <div class="flex">
                      <LabelValue label-class="text-right w-20" label="病区" :value="item.wardName" width="200" />
                      <LabelValue label-class="text-right w-20" label="床位" :value="item.lastBedCode" width="140" />
                    </div>
                    <div class="flex">
                      <LabelValue label-class="text-right w-20" label="入院时间" :value="item.admissionTime" width="200" />
                      <LabelValue label-class="text-right w-20" label="医生" :value="item.lastAttendingDoctorName" width="140" />
                    </div>
                    <LabelValue label-class="text-right w-20" label="入院诊断" :value="item.ryzd" width="300" />
                  </template>
                  <template v-else>
                    <div class="flex">
                      <LabelValue label-class="text-right w-[100px]" label="最近就诊科室" :value="item.ksmc" />
                      <LabelValue label-class="text-right w-[100px]" label="最近就诊医生" :value="item.empName" width="160" />
                    </div>
                    <LabelValue label-class="text-right w-[100px]" label="最近就诊时间" :value="item.ghsj" width="230" />
                    <LabelValue label-class="text-right w-[45px]" label="诊断" :value="item.bcLczdZdmc" width="300" />
                    <CustomerLabel :br-id="item.brId" class="my-3" />
                  </template>
                </div>
              </a-card>
            </template>
          </div>
        </a-spin>
      </div>
      <div class="w-2/3" :class="{ 'w-full': rowData.brId }">
        <a-form :model="formState" class="form-style-flex">
          <a-form-item label="手术" class="w-2/3" v-bind="validateInfos.oprCode">
            <!-- <SelectTable :value="formState.oprName" type="手术" @select=";(formState.oprCode = $event.bh), (formState.oprName = $event.mc)" /> -->
            <a-input v-model:value="formState.oprCode" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="手术等级" class="w-1/3">
            <SelectItem v-model:value="formState.oprLevelCode" type="DT00034" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label="手术日期" class="w-1/3" v-bind="validateInfos.oprDate">
            <a-date-picker v-model:value="formState.oprDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @keydown.enter="onDateEnter" />
          </a-form-item>
          <a-form-item label="手术时间" class="w-1/3" v-bind="validateInfos.oprTime">
            <a-time-picker v-model:value="formState.oprTime" format="HH:mm" value-format="HH:mm" @keydown.enter="onTimeEnter" />
          </a-form-item>
          <a-form-item label="手术房间" class="w-1/3" v-bind="validateInfos.oprRoomName">
            <SelectTable
              v-model:value="formState.oprRoomName"
              type="床位"
              placeholder="请输入"
              :table-width="400"
              :row-disabled="(row) => row.status === 2 || row.status === 1"
              :search-params="{ bqlb: 'QYLB004', wardName: '手术病区' }"
              @select=";(formState.oprRoomName = $event.bedCode), (formState.oprRoomId = $event.id)"
            />
          </a-form-item>
          <a-form-item label="部位" class="w-1/3">
            <a-select
              v-model:value="formState.oprAptmPartList"
              placeholder="请选择"
              mode="multiple"
              max-tag-count="responsive"
              :options="positionList"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="麻醉方式" class="w-1/3">
            <SelectItem v-model:value="formState.anaesCode" type="DT00012" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label="切口等级" class="w-1/3">
            <SelectItem v-model:value="formState.cutLevelCode" type="DT00035" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label="手术入路" class="w-1/3">
            <SelectItem v-model:value="formState.approachCode" type="DT00036" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label="手术分类" class="w-1/3">
            <SelectItem v-model:value="formState.oprTypeCode" type="DT00037" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-form-item label=" " class="w-1/3">
            <a-checkbox v-model:checked="formState.isEcg">心电监护</a-checkbox>
            <a-checkbox v-model:checked="formState.isRecurrence">复发</a-checkbox>
          </a-form-item>
          <a-form-item label="手术医生" class="w-1/3">
            <SelectTable
              v-model:value="formState.oprDoctorName"
              type="医生"
              @select=";(formState.oprDoctor = $event.empId), (formState.oprDoctorName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="麻醉医生" class="w-1/3">
            <SelectTable
              v-model:value="formState.anaesDoctorName"
              type="医生"
              @select=";(formState.anaesDoctor = $event.empId), (formState.anaesDoctorName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="一助" class="w-1/3">
            <SelectTable
              v-model:value="formState.firstNurseName"
              type="医生"
              :search-params="{ emplb: '2' }"
              @select=";(formState.firstNurse = $event.empId), (formState.firstNurseName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="二助" class="w-1/3">
            <SelectTable
              v-model:value="formState.secondNurseName"
              type="医生"
              :search-params="{ emplb: '2' }"
              @select=";(formState.secondNurse = $event.empId), (formState.secondNurseName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="巡回护士" class="w-1/3">
            <SelectTable
              v-model:value="formState.tourNurseName"
              type="医生"
              :search-params="{ emplb: '2' }"
              @select=";(formState.tourNurse = $event.empId), (formState.tourNurseName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="器械护士" class="w-1/3">
            <SelectTable
              v-model:value="formState.instrumenttNurseName"
              type="医生"
              :search-params="{ emplb: '2' }"
              @select=";(formState.instrumenttNurse = $event.empId), (formState.instrumenttNurseName = $event.empName)"
            />
          </a-form-item>
          <a-form-item label="联合手术1" class="w-full">
            <!-- <SelectTable
              v-model:value="formState.jointOprName1"
              type="手术"
              @select=";(formState.jointOprCode1 = $event.bh), (formState.jointOprName1 = $event.mc)"
            /> -->
            <a-input v-model:value="formState.jointOprCode1" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="联合手术2" class="w-full">
            <!-- <SelectTable
              v-model:value="formState.jointOprName2"
              type="手术"
              @select=";(formState.jointOprCode2 = $event.bh), (formState.jointOprName2 = $event.mc)"
            /> -->
            <a-input v-model:value="formState.jointOprCode2" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="特殊要求" class="w-full">
            <a-input v-model:value="formState.specRequirements" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="嘱托" class="w-full">
            <a-textarea v-model:value="formState.advMemo" :rows="5" placeholder="请输入" />
          </a-form-item>
        </a-form>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { post } from '@/utils/request'
import avatarMan from '@/assets/images/avatar-man.png'
import CustomerLabel from '@/components/CustomerLabel'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const loading = ref(false)
const dataSource = ref([])
// const sourceType = ref(1)
const formState = ref({
  oprDate: '',
  oprTime: '',
  oprAptmPartList: undefined,
  oprCode: '',
  oprRoomName: ''
})
const rulesState = ref({
  oprDate: [{ required: true, message: '请选择手术日期' }],
  oprTime: [{ required: true, message: '请选择手术时间' }],
  oprCode: [{ required: true, message: '请选择手术' }],
  oprRoomName: [{ required: true, message: '请选择手术房间' }]
})
const { resetFields, isCompleted, validateInfos } = useForm(formState, rulesState)

//保存手术
const onOk = async () => {
  if (!formState.value.brName) return message.error('姓名不能为空')
  formState.value.isEcg = formState.value.isEcg ? 1 : 0
  formState.value.isRecurrence = formState.value.isRecurrence ? 1 : 0
  const res = await post('/oprOperation/opr/doSaveOperationRecordInfo', formState.value)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  emit('success')
  onCancel()
}

const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
const searchKey = ref('')
//获取病人列表
const getPatientList = async () => {
  loading.value = true
  // /outp/mzdj/getOutpRecordInfoList
  // const url = sourceType.value === 0 ? '/outp/mzdj/getPatientInfoList' : '/inp/zydj/getInpRecordList'
  const { code, data, msg } = await post('/outp/mzdj/getPatientInfoList', { pageNum: 1, pageSize: 10, pyjm: searchKey.value, status: 0 })
  const { data: datas } = await post('/inp/zydj/getInpRecordList', { pageNum: 1, pageSize: 10, pyjm: searchKey.value, status: 0 })
  loading.value = false
  if (code !== 0) return message.error(msg)
  dataSource.value = uniqueData([...datas, ...data])
  !props.rowData.brId && onSelectPatient(dataSource.value[0])
}

// 去重
const uniqueData = (combinedData) => {
  // 使用一个 Set 来跟踪已经见过的 brId
  const seenBrIds = new Set()
  // 使用 filter 方法来去重
  const unique = combinedData.filter((item) => {
    // 检查 jzbh 是否为空，并做判断
    if (item.jzbh) {
      // 如果 jzbh 不为空，且 brId 已经存在，则过滤掉
      if (seenBrIds.has(item.brId)) {
        return false // 过滤掉
      } else {
        seenBrIds.add(item.brId) // 添加到已见过的 brId
        return true // 保留
      }
    } else {
      // 如果 jzbh 为空，直接检查 brId
      if (seenBrIds.has(item.brId)) {
        return false // 过滤掉
      } else {
        seenBrIds.add(item.brId) // 添加到已见过的 brId
        return true // 保留
      }
    }
  })

  return unique
}

const onSelectPatient = (item) => {
  formState.value = {
    // oprPath: sourceType.value,
    keyLsh: item.inplsh, //
    admissionCode: item.admissionCode, //住院号
    brId: item.brId, //病人编号
    brName: item.brName, //病人编号
    brAge: item.brAge, //病人年龄
    brMob: item.brMob, //手机
    brXb: item.brXb //病人性别
  }
}

const positionList = ref([])
//获取部位集合
const getPositionList = async () => {
  const { code, data } = await post('/operation/opex/getDictPartList', { pageNum: 1, pageSize: 999 })
  if (code !== 0) return
  positionList.value = data.map((item) => {
    return {
      value: item.id,
      label: item.partName
    }
  })
}
const onDateEnter = (e) => {
  const dateString = e.target.value
  const regex1 = /^\d{8}$/ // 匹配YYYYMMDD格式
  const regex2 = /^\d{4}-\d{2}-\d{2}$/ // 匹配YYYY-MM-DD格式
  const regex3 = /^\d{4}\/\d{2}\/\d{2}$/ // 匹配YYYY/MM/DD格式
  const regex4 = /^\d{4}\.\d{2}\.\d{2}$/ // 匹配YYYY.MM.DD格式
  // 检查日期字符串是否符合任何一个正则表达式
  const isValidDate = regex1.test(dateString) || regex2.test(dateString) || regex3.test(dateString) || regex4.test(dateString)
  if (isValidDate) {
    formState.value.oprDate = dayjs(dateString).format('YYYY-MM-DD')
    e.target.blur()
  }
}
const onTimeEnter = (e) => {
  const timeString = e.target.value
  const regex1 = /^\d{4}$/ // 匹配HHmm格式
  const isValidTime = regex1.test(timeString)
  if (isValidTime) {
    //HHmm to HH:mm
    formState.value.oprTime = dayjs(timeString, 'HHmm').format('HH:mm')
    e.target.blur()
  }
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      formState.value = { ...props.rowData }
      // getPatientList()
      getPositionList()
    } else {
      dataSource.value = []
      formState.value = {}
      // sourceType.value = 1
      resetFields()
    }
  }
)
</script>
<!-- display: flex;
flex-wrap: wrap;
justify-content: space-between; -->
<style lang="less" scoped>
.card-box {
  height: 650px;
  overflow-x: hidden;
  overflow-y: auto;
  .card-item + .card-item {
    margin-top: 16px;
  }
  .card-item {
    width: 100%;
    height: fit-content;
    cursor: pointer;
    &:hover {
      background-color: #00000005;
      border: 1px solid var(--primary-color);
    }
    &.active {
      border: 1px solid var(--primary-color);
      .item-header {
        color: #fff;
        background-color: var(--primary-color);
      }
    }
    .item-header {
      position: relative;
      display: flex;
      padding: 8px;
      background-color: #00000010;
    }
  }
}
</style>
